<?php
/**
 *	KLF Framework
 *
 *	Written by Kristian Oye <kristianoye@gmail.com> on Oct 22, 2011
 *	Copyright (C) 2010-2011
 */
namespace KLF\System\Config
{
	use KLF\KCore;
	use KLF\System\KComponent;
	use KLF\System\Errors\KFileNotFoundException;
	
	/**
	 *  Class KConfiguration
	 *
	 *  Basic configuration object
	 *
	 *  @package KLF\System\Config
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *  
	 *  @method KConfiguration NewInstance
	 *  
	 *  @property string BaseDirectory
	 *  @property string ConfigurationDirectory
	 *  @property array RawSettings The collection of configuration settings.
	 */
	abstract class KConfiguration extends KComponent
	{
		/**
		 * The file containing the configuration.
		 * @var string
		 */
		protected $_rpropConfigurationFile;
		
		/**
		 * The base directory read from the configuration.
		 * 
		 * @var string $_rpropBaseDirectory
		 */
		protected $_rpropBaseDirectory;
		
		/**
		 * The directory that the configuration resides in. 
		 * 
		 * @var string $_rpropConfigurationDirectory
		 */
		protected $_rpropConfigurationDirectory;
		
		/**
		 * Contains all of the configuration information.
		 * @var array
		 */
		protected $_rpropRawSettings;
		
		/**
		 * Construct a new configuration.
		 * 
		 * @param mixed $parm
		 * @throws KFileNotFoundException
		 */
		public function __construct($parm)
		{
			if (is_string($parm))
			{
				if (!file_exists($parm))
				{
					throw new KFileNotFoundException($parm);
				}
				else 
				{
					$this->_rpropConfigurationFile = $parm;
					
					$buffer = sprintf("namespace %s\n{\n\treturn %s;\n}",
						__NAMESPACE__,  
						file_get_contents($this->_rpropConfigurationFile));
						
					$this->_rpropRawSettings = eval($buffer);
					$includeDir = realpath(dirname($this->_rpropConfigurationFile));
					
					if (is_dir($includeDir))
					{
						$this->_rpropConfigurationDirectory = $includeDir;
					}
					if (isset($this->_rpropRawSettings['basepath']))
					{
						$baseDirectory = realpath($this->_rpropRawSettings['basepath']);
						
						if (strlen($baseDirectory) > 0 && is_dir($baseDirectory))
						{
							$this->_rpropBaseDirectory = $baseDirectory;
							KCore::AddAutoloadDirectories($baseDirectory);
						}
					}
				}
			}
			elseif (is_array($parm))
			{
				if (!isset($this->_rpropRawSettings))
					$this->_rpropRawSettings = $parm;
				else
					$this->_rpropRawSettings = array_merge($this->_rpropRawSettings, $parm);
			}
		}
		
		/**
		 * Fetches a value from the configuration.
		 * 
		 * @param string $key
		 * @param mixed $defaultValue
		 * @return mixed
		 */
		public function GetValue($key = '', $defaultValue = NULL)
		{
			return (isset($this->_rpropRawSettings[$key]) ? 
				$this->_rpropRawSettings[$key] : $defaultValue);
		}
	}
}
